package com.cn.steam.redis;

import com.cn.steam.foundation.common.utils.Op;
import com.cn.steam.redis.model.DistributeProcessor;
import com.cn.steam.redis.model.ServiceProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.*;


@Service
@Slf4j
public class RedisService<K,V> {
    private static final String LOCK_GROUP_KEY = "lock";
    private RedisTemplate<K,V> redisTemplate;// 通过构造方法注入该对象

    public RedisTemplate getTemplate(){
        return redisTemplate;
    }

    public RedisService(RedisTemplate<K,V> redisTemplate){
        super();
        this.redisTemplate = redisTemplate;
        this.redisTemplate.setKeySerializer(new StringRedisSerializer());
    }

    /**
     * 请求超时时间处理器
     *
     * @param processor  业务方法
     * @param timeOut  超时时间  不传默认5秒(大于等于锁的超时时间)
     * @return boolean (成功或者失败)
     */
    private boolean timeOutProcess(ServiceProcessor processor,Long timeOut) throws Exception{
        ExecutorService exec = Executors.newFixedThreadPool(1);
        Callable<Boolean> call = processor::process;
        try {
            Future<Boolean> future = exec.submit(call);
            return future.get(Optional.ofNullable(timeOut).orElse(5000L), TimeUnit.MILLISECONDS); // 任务处理超时时间 ，默认5秒
        } catch (TimeoutException e) {
            log.error("redis分布式锁任务超时:"+e.getMessage(),e);
            return false;
        }finally {
            exec.shutdown();
        }
    }

    /**
     * redis分布式锁，流程：加锁->业务处理->解锁，需要自己处理流程中的异常
     *
     * @param group 分组
     * @param key  唯一key
     * @param processor  业务方法
     * @return boolean (加锁成功或者失败)
     */
    public boolean distributeProcess(String group,K key, DistributeProcessor processor,Long timeOut) throws Exception{
        key = (K)(Op.isNotEmpty(group)?(String.format("%s:%s", group, key)):(String.format("%s:%s", LOCK_GROUP_KEY, key)));
        K finalKey = key;
        return timeOutProcess(()->{
            String requestId = String.valueOf(UUID.randomUUID());
           if(lock(finalKey,requestId)){
                return serviceAndReleaseLock(finalKey,requestId,processor);
            }
            return false;
        },timeOut);
    }

    /**
     * redis分布式锁，流程：加锁->业务处理->解锁，需要自己处理流程中的异常
     *
     * @param key  唯一key
     * @param expiresTime  自定义锁超时时间
     * @param processor  业务方法
     * @return boolean (加锁成功或者失败)
     */
    public boolean distributeProcess(String group,K key,Long expiresTime,DistributeProcessor processor,Long timeOut) throws Exception{
        key = (K)(Op.isNotEmpty(group)?(String.format("%s:%s", group, key)):(String.format("%s:%s", LOCK_GROUP_KEY, key)));
        K finalKey = key;
        return timeOutProcess(()->{
            String requestId = String.valueOf(UUID.randomUUID());
            if(lock(finalKey,requestId,expiresTime)){
                return serviceAndReleaseLock(finalKey,requestId,processor);
            }
            return false;
        },timeOut);
    }

    /**
     * redis分布式锁，流程：业务处理->解锁
     *
     * @param key  唯一key
     * @param requestId  请求者标识
     * @param processor  业务方法
     * @return boolean (加锁成功或者失败)
     */
    private boolean serviceAndReleaseLock(K key,String requestId,DistributeProcessor processor){
        try {
            processor.process();
        }catch (Exception e){
            log.error("redis分布式锁执行业务方法异常："+e.getMessage(),e);
        }finally {
            return releaseLock(key,requestId);
        }
    }

    /**
     * redis分布式锁，加锁
     *
     * @param key  唯一key  默认超时时间为5秒
     * @param requestId  请求者标识
     * @return boolean (加锁成功或者失败)
     */
    private boolean lock(K key,String  requestId) {
        return lock(key,requestId,10000L);
    }

    /**
     * redis分布式锁，加锁
     *
     * @param key  唯一key
     * @param requestId  请求者标识
     * @param expiresTime  自定义锁超时时间
     * @return boolean (加锁成功或者失败)
     */
    private boolean lock(K key, String requestId,Long expiresTime) {
        try{
            String script = "if redis.call('SETNX',KEYS[1],ARGV[1]) == 1 then  return redis.call('PEXPIRE',KEYS[1],ARGV[2])  else return 0 end";
            DefaultRedisScript<Long> longDefaultRedisScript = new DefaultRedisScript<>(script, Long.class);
            Long result = redisTemplate.execute(longDefaultRedisScript, Collections.singletonList(key),requestId, expiresTime);
            return result == 1;
        }catch (Exception e){
            log.error("redis分布式锁加锁异常:"+e.getMessage(),e);
            return false;
        }
    }

    /**
     * redis分布式锁，解锁
     *
     * @param key  唯一key
     * @param requestId  请求者标识
     */
    private boolean releaseLock(K key,String requestId) {
        try {
            String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
            DefaultRedisScript<Long> longDefaultRedisScript = new DefaultRedisScript<>(script, Long.class);
            Long result = redisTemplate.execute(longDefaultRedisScript, Collections.singletonList(key),requestId);
            return result == 1;
        }catch (Exception e){
            log.error("redis分布式锁释放锁异常:"+e.getMessage(),e);
            return  false;
        }
    }

    /**
     * 普通缓存获取
     *
     * @param pattern 匹配表达式
     * @return 值
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Set<String> keys(K pattern) {
        return (Set<String>) redisTemplate.keys(pattern);
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Set<K> keys(String group,K pattern) {
        if(Op.isEmpty(group)) return null;
        return redisTemplate.keys((K)String.format("%s:%s", group, pattern));
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param milliseconds 时间(豪秒)
     * @return boolean
     */
    public boolean expire(K key, long milliseconds) {
        try {
            if (milliseconds > 0) {
                redisTemplate.expire(key, milliseconds, TimeUnit.MILLISECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean expire(String group,K key, long milliseconds) {
        if(Op.isEmpty(group)) return false;
        try {
            if (milliseconds > 0) {
                redisTemplate.expire((K)String.format("%s:%s", group,key), milliseconds, TimeUnit.MILLISECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(豪秒) 返回0代表为永久有效
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Long getExpire(K key) {
        return redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Long getExpire(String group,K key) {
        if(Op.isEmpty(group)) return null;
        return redisTemplate.getExpire((K)String.format("%s:%s", group,key), TimeUnit.MILLISECONDS);
    }
    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public boolean hasKey(K key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public boolean hasKey(String group,K key) {
        if(Op.isEmpty(group)) return false;
        try {
            return redisTemplate.hasKey((K)String.format("%s:%s", group,key));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(K... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 删除缓存
     *
     * @param keys
     */
    public void del(List<K> keys) {
        if (Op.isNotEmpty(keys)) {
            if (keys.size() == 1) {
                redisTemplate.delete(keys.get(0));
            } else {
                redisTemplate.delete(keys);
            }
        }
    }

    public void del(boolean isGroup,String group,K... key) {
        if(isGroup){
            if(Op.isEmpty(group)) return;
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    redisTemplate.delete((K)String.format("%s:%s", group,key[0]));
                } else {
                    List keys = CollectionUtils.arrayToList(key);
                    keys.forEach(x->{
                        x = String.format("%s:%s", group,x);
                    });
                    redisTemplate.delete(keys);
                }
            }
        }else{
            del(key);
        }

    }

    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public V get(K key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public V get(String group,K key) {
        return key == null || Op.isEmpty(group)? null : redisTemplate.opsForValue().get((K)String.format("%s:%s", group,key));
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(K key, V value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    public boolean set(String group,K key, V value) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForValue().set((K)String.format("%s:%s", group,key), value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param milliseconds  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(K key, V value, long milliseconds) {
        try {
            if (milliseconds > 0) {
                redisTemplate.opsForValue().set(key, value, milliseconds, TimeUnit.MILLISECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(String group,K key, V value, long milliseconds) {
        if(Op.isEmpty(group)) return false;
        try {
            if (milliseconds > 0) {
                redisTemplate.opsForValue().set((K)String.format("%s:%s", group,key), value, milliseconds, TimeUnit.MILLISECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(String group, K key, V value, long milliseconds, TimeUnit unit) {
        if(Op.isEmpty(group)) return false;
        try {
            if (milliseconds > 0) {
                redisTemplate.opsForValue().set((K)String.format("%s:%s", group,key), value, milliseconds, unit);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean setnx(K key, V value, long milliseconds){
        try {
            if (milliseconds > 0) {
                redisTemplate.opsForValue().setIfAbsent(key, value, milliseconds, TimeUnit.MILLISECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean setnx(String group,K key, V value, long milliseconds){
        if(Op.isEmpty(group)) return false;
        try {
            if (milliseconds > 0) {
                redisTemplate.opsForValue().setIfAbsent((K)String.format("%s:%s", group,key), value, milliseconds, TimeUnit.MILLISECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean setnx(String group, K key, V value, long milliseconds, TimeUnit unit){
        if(Op.isEmpty(group)) return false;
        try {
            if (milliseconds > 0) {
                redisTemplate.opsForValue().setIfAbsent((K) String.format("%s:%s", group,key), value, milliseconds, unit);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(K key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    public long incr(String group,K key, long delta) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment((K)String.format("%s:%s", group,key), delta);
    }
    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(K key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    public long decr(String group,K key, long delta) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment((K)String.format("%s:%s", group,key), -delta);
    }
    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Object hGet(K key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Object hGet(String group,K key, String item) {
        if(Op.isEmpty(group)) return null;
        return redisTemplate.opsForHash().get((K)String.format("%s:%s", group,key), item);
    }
    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Map<Object, Object> hGet(K key) {
        return redisTemplate.opsForHash().entries(key);
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Map<Object, Object> hGet(String group,K key) {
        if(Op.isEmpty(group)) return null;
        return redisTemplate.opsForHash().entries((K)String.format("%s:%s", group,key));
    }
    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hSet(K key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean hSet(String group,K key, Map<String, Object> map) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForHash().putAll((K)String.format("%s:%s", group,key), map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param milliseconds 时间(毫秒)
     * @return true成功 false失败
     */
    public boolean hSet(K key, Map<String, Object> map, long milliseconds) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (milliseconds > 0) {
                expire(key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean hSet(String group,K key, Map<String, Object> map, long milliseconds) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForHash().putAll((K)String.format("%s:%s", group,key), map);
            if (milliseconds > 0) {
                expire(group,key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hSet(K key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean hSet(String group,K key, String item, Object value) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForHash().put((K)String.format("%s:%s", group,key), item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param milliseconds  时间(毫秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hSet(K key, String item, Object value, long milliseconds) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (milliseconds > 0) {
                expire(key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean hSet(String group,K key, String item, Object value, long milliseconds) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForHash().put((K)String.format("%s:%s", group,key), item, value);
            if (milliseconds > 0) {
                expire(group,key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hDel(K key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    public void hDel(String group,K key, Object... item) {
        if(Op.isEmpty(group)) return;
        redisTemplate.opsForHash().delete((K)String.format("%s:%s", group,key), item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public boolean hHasKey(K key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public boolean hHasKey(String group,K key, String item) {
        if(Op.isEmpty(group)) return false;
        return redisTemplate.opsForHash().hasKey((K)String.format("%s:%s", group,key), item);
    }
    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */
    public double hIncr(K key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    public double hIncr(String group,K key, String item, double by) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        return redisTemplate.opsForHash().increment((K)String.format("%s:%s", group,key), item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    public double hDecr(K key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    public double hDecr(String group,K key, String item, double by) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        return redisTemplate.opsForHash().increment((K)String.format("%s:%s", group,key), item, -by);
    }

    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Set<V> sGet(K key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Set<V> sGet(String group,K key) {
        if(Op.isEmpty(group)) return null;
        try {
            return redisTemplate.opsForSet().members((K)String.format("%s:%s", group,key));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public boolean sHasKey(K key, V value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public boolean sHasKey(String group,K key, V value) {
        if(Op.isEmpty(group)) return false;
        try {
            return redisTemplate.opsForSet().isMember((K)String.format("%s:%s", group,key), value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(K key, V... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public long sSet(String group,K key, V... values) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        try {
            return redisTemplate.opsForSet().add((K)String.format("%s:%s", group,key), values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param milliseconds   时间(毫秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(K key, long milliseconds, V... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (milliseconds > 0) {
                expire(key, milliseconds);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public long sSetAndTime(String group,K key, long milliseconds, V... values) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        try {
            Long count = redisTemplate.opsForSet().add((K)String.format("%s:%s", group,key), values);
            if (milliseconds > 0) {
                expire(group,key, milliseconds);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return long
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public long sGetSetSize(K key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public long sGetSetSize(String group,K key) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        try {
            return redisTemplate.opsForSet().size((K)String.format("%s:%s", group,key));
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(K key, V... values) {
        try {
            return redisTemplate.opsForSet().remove(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public long setRemove(String group,K key, V... values) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        try {
            return redisTemplate.opsForSet().remove((K)String.format("%s:%s", group,key), values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public List<V> lGet(K key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public List<V> lGet(String group,K key, long start, long end) {
        if(Op.isEmpty(group)) return null;
        try {
            return redisTemplate.opsForList().range((K)String.format("%s:%s", group,key), start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public long lGetListSize(K key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public long lGetListSize(String group,K key) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        try {
            return redisTemplate.opsForList().size((K)String.format("%s:%s", group,key));
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
     * @return
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Object lGetIndex(K key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public Object lGetIndex(String group,K key, long index) {
        if(Op.isEmpty(group)) return null;
        try {
            return redisTemplate.opsForList().index((K)String.format("%s:%s", group,key), index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(K key, V value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean lSet(String group,K key, V value) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForList().rightPush((K)String.format("%s:%s", group,key), value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param milliseconds  时间(毫秒)
     * @return
     */
    public boolean lSet(K key, V value, long milliseconds) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (milliseconds > 0) {
                expire(key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean lSet(String group,K key, V value, long milliseconds) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForList().rightPush((K)String.format("%s:%s", group,key), value);
            if (milliseconds > 0) {
                expire(group,key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(K key, List<V> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean lSet(String group,K key, List<V> value) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForList().rightPushAll((K)String.format("%s:%s", group,key), value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param milliseconds  时间(毫秒)
     * @return boolean
     */
    public boolean lSet(K key, List<V> value, long milliseconds) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (milliseconds > 0) {
                expire(key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean lSet(String group,K key, List<V> value, long milliseconds) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForList().rightPushAll((K)String.format("%s:%s", group,key), value);
            if (milliseconds > 0) {
                expire(group,key, milliseconds);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return boolean
     */
    public boolean lUpdateIndex(K key, long index, V value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            log.error("根据索引修改list中数据异常:"+e.getMessage(),e);
            return false;
        }
    }

    public boolean lUpdateIndex(String group,K key, long index, V value) {
        if(Op.isEmpty(group)) return false;
        try {
            redisTemplate.opsForList().set((K)String.format("%s:%s", group,key), index, value);
            return true;
        } catch (Exception e) {
            log.error("根据索引修改list中数据异常:"+e.getMessage(),e);
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(K key, long count, Object value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            log.error("移除多个缓存异常:"+e.getMessage(),e);
            return 0;
        }
    }

    public long lRemove(String group,K key, long count, Object value) {
        if(Op.isEmpty(group)) throw new RuntimeException("分组不能为空");
        try {
            return redisTemplate.opsForList().remove((K)String.format("%s:%s", group,key), count, value);
        } catch (Exception e) {
            log.error("移除多个缓存异常:"+e.getMessage(),e);
            return 0;
        }
    }
    /**
     * 按键的排序获取对应的值
     *
     * @param keys 多个键
     * @return List<Object>
     */
    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public List<V> mGet(Collection<K> keys) {
        return redisTemplate.opsForValue().multiGet(keys);
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
    public List<V> mGet(String group,Collection<K> keys) {
        if(Op.isEmpty(group)) return null;
        keys.forEach(x->{
            x =(K)String.format("%s:%s", group,x);
        });
        return redisTemplate.opsForValue().multiGet(keys);
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key 键
     * @return boolean
     */
    public boolean exists(final K key) {
        return redisTemplate.hasKey(key);
    }

    public boolean exists(String group,final K key) {
        if(Op.isEmpty(group)) return false;
        return redisTemplate.hasKey((K)String.format("%s:%s", group,key));
    }

}
